<template>
  <div class="signin-container">
    <!-- 左侧日历组件 -->
    <div class="calendar-container">
      <!-- <div class="calendar-card"> -->
      <!-- <span>签到日历</span> -->
      <el-calendar class="calendar-body" v-model="currentDate" :first-day-of-week="1">
        <template #date-cell="{ data }">
          <div class="calendar-cell">
            <span :class="['signin-mark', { 'signed': isSignedOnDate(data.day) }]"></span>
            <span class="date-text">{{ data.day.split('-').slice(2).join('-') }}</span>
          </div>
        </template>
      </el-calendar>
      <div class="legend">
        <div class="legend-item">
          <span class="legend-dot signed"></span>
          <span>已签到</span>
        </div>
        <!-- </div> -->
      </div>
    </div>

    <!-- 右侧签到卡片 -->
    <div class="signin-card">
      <div class="card-header">
        <h2 class="title">学生签到系统</h2>
        <div class="student-info">
          <div class="avatar">{{ userInitial }}</div>
          <div class="info">
            <div class="student-name">{{ data.userName }}</div>
            <div class="student-id">昵称: {{ data.nickName }}</div>
          </div>
        </div>
      </div>
      <div class="card-body">
        <!-- 课程信息 -->
        <div class="task-info" v-if="showDetail">
          <div class="icon-back" @click="showDetail = false">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="24"
              height="24"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              class="lucide lucide-arrow-up-left-icon lucide-arrow-up-left"
            >
              <path d="M7 17V7h10" />
              <path d="M17 17 7 7" />
            </svg>
          </div>
          <div class="task-name">{{ currentTask.name }}</div>
          <div class="task-time">
            <span>{{ currentTask.startTime }} 至 {{ currentTask.endTime }}</span>
          </div>
          <div class="task-teacher">教师: {{ currentTask.teacher }}</div>
        </div>
        <!-- 任务列表 -->
        <div class="task-list" v-else>
          <TimeLine class="time-line" layout="vertical" align="alternate" :value="userTasks">
            <template #content="slotProps">
              <el-card class="task-card" @click="toTaskDetail(slotProps.item)">
                <template #header>
                  {{ slotProps.item.name }}
                </template>
                <span class="time"> {{ slotProps.item.startTime }}-{{ slotProps.item.endTime }} </span>
              </el-card>
            </template>
          </TimeLine>
        </div>

        <!-- 签到状态 -->
        <div class="signin-status" v-if="showDetail">
          <!-- <template >

          </template> -->
          <!-- 当未请假时显示签到和签退相关内容 -->
          <template v-if="leaveStatus === 'none'">
            <div class="status-item" :class="{ 'signed': isSigned }">
              <svg-icon :icon-class="isSigned ? 'success' : 'clock'" class="status-icon" />
              <span class="status-text">{{ isSigned ? '已签到' : '未签到' }}</span>
              <span v-if="isSigned" class="signin-time">{{ signinTime }}</span>
            </div>

            <!-- 签到按钮 -->
            <el-button v-if="!isSigned" type="primary" size="large" :loading="isSigning" @click="handleSignIn" class="signin-btn">
              {{ isSigning ? '签到中...' : '立即签到' }}
            </el-button>

            <!-- 已签到但未签退的情况 -->
            <div v-if="isSigned && !isCheckedOut" class="checkout-section">
              <div class="status-item">
                <svg-icon icon-class="logout" class="status-icon" />
                <span class="status-text">未签退</span>
              </div>

              <!-- 签退按钮 -->
              <el-button type="warning" size="large" :loading="isCheckingOut" @click="handleCheckOut" class="checkout-btn">
                {{ isCheckingOut ? '签退中...' : '立即签退' }}
              </el-button>
            </div>

            <!-- 已完成签退的情况 -->
            <div v-if="isSigned && isCheckedOut" class="checkout-section">
              <div class="status-item checked-out">
                <svg-icon icon-class="success" class="status-icon" />
                <span class="status-text">已签退</span>
                <span class="signin-time">{{ checkoutTime }}</span>
              </div>

              <!-- 已完成全流程提示 -->
              <div class="checked-out-tip">
                <svg-icon icon-class="check" class="check-icon" />
                <span>您已完成签到和签退，今天辛苦啦！🥰🥰🥰</span>
              </div>
            </div>

            <!-- 已签到但不需要签退时的提示 -->
            <div v-if="isSigned && !isCheckedOut && !showCheckoutButton" class="signed-tip">
              <svg-icon icon-class="check" class="check-icon" />
              <span>您已完成签到，感谢配合！</span>
            </div>
          </template>

          <!-- 请假状态显示 -->
          <div v-if="leaveStatus !== 'none'" class="leave-status-section">
            <div v-if="leaveStatus === 'applying'" class="leave-status-item applying">
              <svg-icon icon-class="clock" class="status-icon" />
              <span class="status-text">正在申请请假……</span>
            </div>
            <div v-else-if="leaveStatus === 'approved'" class="leave-status-item approved">
              <svg-icon icon-class="success" class="status-icon" />
              <span class="status-text">已请假</span>
            </div>
          </div>
        </div>
      </div>
      <!-- 请假申请按钮 -->
      <div class="leave-button-container" style="position: relative; top: -80px">
        <el-button type="primary" :loading="isSubmittingLeave" @click="showLeaveDialog = true" class="leave-button"> 我要请假 </el-button>
      </div>

      <!-- 请假申请对话框 -->
      <el-dialog v-model="showLeaveDialog" title="请假申请" width="500px" :before-close="handleCloseDialog">
        <div class="leave-dialog-content">
          <el-form :model="leaveForm" :rules="leaveRules" ref="leaveFormRef">
            <el-form-item prop="reason">
              <el-input v-model="leaveForm.reason" type="textarea" :rows="4" placeholder="请输入请假原因" />
            </el-form-item>
            <el-form-item prop="proof" label="证明材料 (可选)">
              <el-upload class="upload-demo" drag action="" :on-change="handleFileChange" :on-remove="handleFileRemove" :auto-upload="false" multiple>
                <el-icon class="el-icon--upload"><Upload /></el-icon>
                <div class="el-upload__text">点击或拖拽文件到此处上传</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleLeaveSubmit" :loading="isSubmittingLeave">提交请假申请</el-button>
        </template>
      </el-dialog>

      <!-- 底部版权信息 -->
    </div>
  </div>
  <div class="footer">
    <span>© 2025 202小作坊 - 技术支持</span>
  </div>
</template>

<script setup lang="ts">
import { listRecord } from '@/api/signIn/record/index';
import api from '@/api/system/user';
import { useUserStore } from '@/store/modules/user';
import { addRecord, getUserTaskSignInRecord } from '@/api/signIn/record';
import { listTaskForUser } from '@/api/signIn/task';
import { TaskVO } from '@/api/signIn/task/types';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import TimeLine from 'primevue/timeline';
import { ElLoading, ElCalendar } from 'element-plus';
import { watch } from 'vue';
const router = useRouter();

const loadingInstance = ElLoading.service({
  lock: true,
  text: '获取任务列表中',
  background: 'rgba(0, 0, 0, 0.7)'
});

// 学生信息
const data = reactive({
  userName: '',
  nickName: ''
});
const userInitial = computed(() => data.userName.charAt(0));

/** 查询用户列表 */
const userId = ref();
const getList = async () => {
  userId.value = useUserStore().userId;
  const res = await api.optionSelect(userId.value);
  data.userName = res.data[0].userName;
  data.nickName = res.data[0].nickName;
};
getList();

// 用户任务列表
const userTasks = ref<TaskVO[]>([]);

// 当前日期（用于日历组件）
const currentDate = ref(new Date());

// 已签到的日期集合
const signedDates = ref<Set<string>>(new Set());

// 课程信息
const currentTask = ref<TaskVO>();

// 签到/签退/请假相关响应式数据
const isSigned = ref(false);
const isSigning = ref(false);
const signinTime = ref('');
const isCheckedOut = ref(false);
const isCheckingOut = ref(false);
const checkoutTime = ref('');
const showLeaveDialog = ref(false);
const isSubmittingLeave = ref(false);
const showCheckoutButton = ref(true);
const leaveStatus = ref<'none' | 'applying' | 'approved'>('none');

// 请假表单
const leaveForm = ref({ reason: '', proof: [] });
const leaveFormRef = ref();
const leaveRules = {
  reason: [
    { required: true, message: '请输入请假原因', trigger: 'blur' },
    { min: 8, message: '请假原因至少需要8个字符', trigger: 'blur' }
  ]
};
const showDetail = ref(false);
const toTaskDetail = (task: TaskVO) => {
  showDetail.value = true;
  currentTask.value = task;
  checkSignInStatus();
};

const handleCloseDialog = () => {
  showLeaveDialog.value = false;
  leaveForm.value = { reason: '', proof: [] };
  if (leaveFormRef.value) leaveFormRef.value.resetFields();
};

const handleSignIn = async () => {
  isSigning.value = true;
  try {
    // await new Promise(resolve => setTimeout(resolve, 1000));
    const totalRes = await getUserTaskSignInRecord(userId.value, currentTask.value.id);
    if (totalRes.total < 1) {
      await addRecord({
        userId: userId.value,
        taskId: currentTask.value.id
      });
      checkSignInStatus();
    }
    ElMessage.success('签到成功');
  } catch {
    ElMessage.error('签到失败，请重试');
  } finally {
    checkSignInStatus();
    isSigning.value = false;
  }
};

const handleCheckOut = async () => {
  isCheckingOut.value = true;
  try {
    // await new Promise(resolve => setTimeout(resolve, 1000));
    isCheckedOut.value = true;
    const totalRes = await getUserTaskSignInRecord(userId.value, currentTask.value.id);
    if (totalRes.total! < 2) {
      await addRecord({
        userId: userId.value,
        taskId: currentTask.value.id
      });
    }
    ElMessage.success('签退成功！');
  } catch {
    ElMessage.error('签退失败，请重试');
  } finally {
    checkSignInStatus();
    isCheckingOut.value = false;
  }
};

const handleFileChange = (_file: any, fileList: any[]) => {
  leaveForm.value.proof = fileList;
};
const handleFileRemove = (_file: any, fileList: any[]) => {
  leaveForm.value.proof = fileList;
};

const handleLeaveSubmit = async () => {
  if (!leaveFormRef.value) return;
  leaveFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        isSubmittingLeave.value = true;
        await new Promise((resolve) => setTimeout(resolve, 1000));
        ElMessage.success('请假申请提交成功，请等待审批');
        leaveStatus.value = 'applying';
        showLeaveDialog.value = false;
        leaveForm.value = { reason: '', proof: [] };
        if (leaveFormRef.value) leaveFormRef.value.resetFields();
      } catch {
        ElMessage.error('提交失败，请重试');
      } finally {
        isSubmittingLeave.value = false;
      }
    }
  });
};

onMounted(async () => {
  await getList(); // Ensure userId is available before fetching tasks
  console.log('getList执行完了');
  await fetchUserTasks();
  await fetchSignedDates();
});

const isCheckingStatus = ref(false);
const checkSignInStatus = async () => {
  isCheckingStatus.value = true;
  // 可在此处初始化签到状态
  console.log('hahahlololo');
  const totalRes = await getUserTaskSignInRecord(userId.value, currentTask.value.id);
  console.log('totalRes:', totalRes);
  if (totalRes.total == 1) {
    isSigned.value = true;
    isCheckedOut.value = false;
    signinTime.value = totalRes.rows.find((value) => !value.relatedSignId).createTime.substring(11);
  }
  if (totalRes.total == 2) {
    isSigned.value = true;
    isCheckedOut.value = true;
    signinTime.value = totalRes.rows.find((value) => !value.relatedSignId).createTime.substring(11);
    checkoutTime.value = totalRes.rows.find((value) => value.relatedSignId).createTime.substring(11);
  }
  if (totalRes.total == 0) {
    isSigned.value = false;
    isCheckedOut.value = false;
  }
  isCheckingStatus.value = false;
};

const fetchUserTasks = async () => {
  try {
    const res = await listTaskForUser(userId.value);
    res.rows.forEach((value) => {
      value.startTime = value.startTime.substring(11);
      value.endTime = value.endTime.substring(11);
    });
    userTasks.value = res.rows;
  } catch (error) {
    ElMessage.error('获取任务列表失败');
  } finally {
    loadingInstance.close();
    console.log('loadingInstance关掉了');
  }
};

// 获取用户签到记录并更新日历
const fetchSignedDates = async () => {
  try {
    const year = currentDate.value.getFullYear();
    const month = currentDate.value.getMonth() + 1;
    const res = await listRecord();

    // 清空现有记录
    signedDates.value.clear();

    // 添加新记录到集合
    if (res && res.rows) {
      res.rows.forEach((record: any) => {
        // 格式化日期为 YYYY-MM-DD 格式
        const date = new Date(record.createTime);
        // 只添加当前月份的签到记录
        if (date.getFullYear() === year && date.getMonth() + 1 === month) {
          const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
          signedDates.value.add(formattedDate);
        }
      });
      console.log('日历签到数据:', res.rows);
    }
  } catch (error) {
    console.error('获取签到记录失败', error);
  }
};

// 当API调不通时，添加一些模拟数据
const mockSignedDates = () => {
  const today = new Date();
  const year = today.getFullYear();
  const month = today.getMonth() + 1;

  // 添加过去几天的模拟签到记录
  for (let i = 0; i < 5; i++) {
    const date = new Date(today);
    date.setDate(date.getDate() - i * 2); // 每隔一天添加一个签到记录
    const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    signedDates.value.add(formattedDate);
  }
};

// 检查指定日期是否已签到
const isSignedOnDate = (dateString: string) => {
  return signedDates.value.has(dateString);
};

// 监听日期变化，重新获取签到记录
watch(currentDate, () => {
  fetchSignedDates();
});
</script>

<style lang="scss" scoped>
.calendar-body {
  border-radius: 10px;
  padding: 13px;
}

.icon-back {
  float: left;
  cursor: pointer;
}

.signin-container {
  width: 100vw;
  min-height: 92vh;
  display: flex;
  flex-direction: row;
  justify-content: center;
  padding: 40px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-size: cover;
  background-attachment: fixed;
}

.signin-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 180%;
  height: 62vh;
  max-width: 600px;
  margin-bottom: 30px;
  transition: transform 0.3s ease;
}

.card-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
}

.student-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
  margin-right: 15px;
}

.info {
  display: flex;
  flex-direction: column;
}

.student-name {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.student-id {
  font-size: 14px;
  color: #666;
}

.task-info {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.time-line {
  width: 100%;
}

.task-name {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.task-time {
  display: flex;
  justify-content: center;
  gap: 20px;
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
}

.task-teacher {
  font-size: 14px;
  color: #888;
}

.signin-status {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.status-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 15px 30px;
  border-radius: 8px;
  background: #f8f9fa;
  margin-bottom: 20px;
  width: 100%;
  max-width: 300px;
}

.status-item.signed {
  background: #e8f5e9;
}

.status-icon {
  font-size: 20px;
  color: #666;
}

.status-item.signed .status-icon {
  color: #4caf50;
}

.status-item.checked-out {
  background: #fff3e0;
}

.status-item.checked-out .status-icon {
  color: #ff9800;
}

.status-text {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.signin-time {
  font-size: 14px;
  color: #888;
  margin-left: 10px;
}

.signin-btn {
  width: 100%;
  max-width: 300px;
  height: 50px;
  font-size: 18px;
  font-weight: 500;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
}

.signin-btn:hover {
  transform: scale(1.02);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.signed-tip {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #4caf50;
  font-size: 16px;
  font-weight: 500;
}

.checkout-section {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.checkout-btn {
  width: 100%;
  max-width: 300px;
  height: 50px;
  font-size: 18px;
  font-weight: 500;
  background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
  border: none;
  transition: all 0.3s ease;
  margin-top: 20px;
}

.checkout-btn:hover {
  transform: scale(1.02);
  box-shadow: 0 5px 15px rgba(255, 152, 0, 0.4);
}

.checked-out-tip {
  display: flex;
  align-items: center;
  gap: 10px;
  // color: #ff9800;
  color: #48a39f;
  font-size: 16px;
  font-weight: 500;
  margin-top: 20px;
}

.check-icon {
  font-size: 20px;
}

.leave-button-container {
  margin-top: 20px;
  width: 100%;
  max-width: 600px;
  display: flex;
  justify-content: center;
}

.leave-button {
  padding: 12px 30px;
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.leave-icon {
  color: white;
}

.leave-dialog-content {
  padding: 10px 0;
}

.footer {
  position: absolute;
  bottom: 20px;
  width: 100%;
  text-align: center;
  margin-top: 180px;
  color: white;
  font-size: 14px;
  opacity: 0.8;
}

.time {
  font-size: small;
}

.task-card {
  cursor: pointer;
}

.card-body {
  height: 70%;
  overflow-y: scroll;
}

// 适配移动端
@media (max-width: 768px) {
  .signin-container {
    padding: 20px 15px;
  }

  .signin-card {
    padding: 30px 20px;
  }

  .title {
    font-size: 22px;
  }

  .task-name {
    font-size: 18px;
  }

  .leave-container {
    padding: 0;
  }

  .leave-header {
    padding: 20px;
  }

  .leave-form {
    padding: 20px;
  }
}

/* 请假状态样式 */
.leave-status-section {
  margin-top: 16px;
  width: 100%;
  max-width: 300px;
}

.leave-status-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 15px 30px;
  border-radius: 8px;
  width: 100%;
}

.leave-status-item.applying {
  background: #fff7e6;
  color: #faad14;
}

.leave-status-item.approved {
  background: #e8f5e9;
  color: #4caf50;
}

.task-timeline-container {
  margin-top: 30px;
  width: 100%;
  max-width: 800px;
  padding: 0 20px;
}

.timeline-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.timeline-item {
  padding-bottom: 20px;
}

.task-card {
  cursor: pointer;
  transition: transform 0.2s ease;
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  }
}

.task-card h4 {
  margin-top: 0;
  margin-bottom: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.task-remark {
  font-size: 14px;
  color: #666;
  margin-bottom: 0;
}

.timeline {
  border: 1px solid red;
  height: 100px;
}
/* 日历样式 */
.calendar-container {
  max-width: 600px;
  margin-right: 40px;
  height: 70vh;
}

.calendar-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 0 30px 30px 30px;
  height: 60vh;
  display: flex;
  flex-direction: column;
}

.calendar-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  // margin-bottom: 20px;
  text-align: center;
  margin: 0;
  padding: 0;
}

.calendar-cell {
  position: relative;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.signin-mark {
  position: absolute;
  bottom: 2px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  opacity: 0;
}

.signin-mark.signed {
  background: #4caf50;
  opacity: 1;
}

.date-text {
  font-size: 14px;
  color: #333;
}

.legend {
  display: flex;
  justify-content: center;
  margin-top: -30px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #666;
}

.legend-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #ddd;
}

.legend-dot.signed {
  background: #4caf50;
}

/* 响应式布局调整 */
@media (max-width: 1200px) {
  .signin-container {
    flex-direction: column;
    align-items: center;
  }

  .calendar-container {
    margin-right: 0;
    margin-bottom: 30px;
    max-width: 600px;
  }

  .calendar-card {
    height: auto;
    max-height: 900px;
  }
}

/* 适配移动端 */
@media (max-width: 768px) {
  .calendar-container {
    padding: 0 15px;
  }

  .calendar-card {
    padding: 20px 15px;
  }
}
</style>
